package com.github.edu.security.login.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.github.admin.edu.assembly.common.entity.JsonEntity;
import com.github.admin.edu.assembly.common.util.JsonUtils;
import com.github.admin.edu.oauth.server.api.entity.SecurityUser;
import com.github.admin.edu.oauth.server.api.entity.TSysUser;
import com.github.edu.security.login.domain.UserLoginDomain;
import com.github.edu.security.login.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.StringUtils;

/**
 * Create by IntelliJ IDEA
 * 用户：王建
 * 日期：2018-4-16
 */
public class UserServiceImpl implements UserService,UserDetailsService {

    @Value("${server.custom.login.enabled}")
    private boolean enabled;

    @Autowired
    private UserLoginDomain domain;

    public TSysUser getUser(String userId){
        String code= null;
        if(enabled){
            code=domain.getSysEntity(userId);
        }else {
            code=domain.getEntity(userId);
        }
        if(!StringUtils.isEmpty(code)){
            JsonEntity<TSysUser> jsonEntity=JsonUtils.toCollection(code, new TypeReference<JsonEntity<TSysUser>>() {});
            TSysUser tuser=jsonEntity.getData();
            return tuser;
        }
        return null;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TSysUser user = getUser(username);
        if (user == null) {
            throw new UsernameNotFoundException("UserName " + username + " not found");
        }
        SecurityUser securityUser = new SecurityUser(user);
        return securityUser;
    }
}
